﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace Alfa.Common.ValidationRules {
	class DateTimeRangeValidationRule : ValidationRuleBase {
		public DateTimeRangeValidationRule( ) { }

		public bool Nullable { get; set; }
		public DateTime? Min { get; set; }
		public DateTime? Max { get; set; }

		public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
			DateTime? dateTime = null;

			if (Min > Max) // Does Min is greater than Max?
				throw new Exception("Min range criteria cannot be greater than Max range criteria.");

			if (value is DateTime) { // Does value is already DateTime?

			} else if (value == null) {
				if (!this.Nullable)
					return this.ParseError(false, Messages.NotADateTime);
			} else if (value is string) { // Does value is string?
				if (((string)value).Length > 0) {
					DateTime parsedDateTime;
					if (!DateTime.TryParse((string)value, out parsedDateTime)) // Does value is long?
						return this.ParseError(false, Messages.NotANumber);
					else
						dateTime = parsedDateTime;
				} else if (!this.Nullable)
					return this.ParseError(false, Messages.NotANumber);
			} else { // Value can not be any numeric type
				throw new ArgumentException(this.GetType( ).ToString( ) + " validator can not validate provided value (Type " + (value != null ? value.GetType( ).ToString( ) : "null") + " is not supported)!");
			}

			if ((Min.HasValue && dateTime < Min) || (Max.HasValue && dateTime > Max)) { // Is number in range?
				return this.ParseError(false, Messages.PleaseEnterADateInTheRange + (Min.HasValue ? Min.ToString( ) : "") + " - " + (Max.HasValue ? Max.ToString( ) : "") + ".");
			} else {
				return this.ParseError(true, null);
			}
		}
	}
}
